package com.qili.core.quartz.CustomQuartz;

import cn.hutool.core.util.IdUtil;
import com.qili.entity.supervisor.SupervisorProject;
import com.qili.entity.supervisor.SupervisorProjectMilepost;
import com.qili.entity.supervisor.SupervisorProjectStage;
import com.qili.entity.supervisor.dto.SupervisorProjectDTO;
import com.qili.entity.supervisor.dto.SupervisorProjectStageDTO;
import com.qili.entity.supplier.SupplierProjectPubNotice;
import com.qili.entity.sys.SysUser;
import com.qili.redis.RedisService;
import com.qili.service.SysUserService;
import com.qili.service.base.*;
import com.qili.service.supervisor.*;
import com.qili.service.supplier.SupplierProjectPubNoticeService;
import com.qili.service.sys.SysRegionService;
import com.qili.util.DateUtil;
import com.qili.util.StringUtil;
import com.qili.util.UploadUtil;
import lombok.extern.java.Log;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import tk.mybatis.mapper.entity.Example;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author zhaoyongke
 * @date 2021/4/7
 * @description 自动修改公示状态job
 */
@Log
public class GsNoticeJob implements Job {
    @Autowired
    SysUserService sys;
    @Autowired
    private SupplierProjectPubNoticeService supplierProjectPubNoticeService;

    @Autowired
    private RedisService redisService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        System.out.println("GsNoticeJob：启动任务=======================");

        log.info("GsNoticeJob=======开始==================================");
        String lockkey = "GsNoticeJob_key";
        String uuId = IdUtil.simpleUUID();
        try {
            run();
            System.out.println("JobDemo1：下次执行时间=====" +
                    new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
                            .format(context.getNextFireTime()) + "==============");
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        } finally {
            unlock(lockkey, uuId);
        }
    }

    public void run() {
        try {
            // 供需  ----公示期设置定时任务，公示期结束后下午17:30给中标应接人/中标组织发送信息，无论中标与否都需要在待办事宜的站内信提醒。

            Example ecj = new Example(SupplierProjectPubNotice.class);
            Example.Criteria ccj = ecj.createCriteria();
            ccj.andNotEqualTo("gsStatus", "2");
            List<SupplierProjectPubNotice> list = supplierProjectPubNoticeService.selectByExample(ecj);

            for (int i = 0; i < list.size(); i++) {
                SupplierProjectPubNotice supplierProjectPubNotice = list.get(i);
                String startDate = supplierProjectPubNotice.getStartDate();
                String endDate = supplierProjectPubNotice.getEndDate();
                String gsStatus = supplierProjectPubNotice.getGsStatus() + "";
                String status = "";
                if (StringUtil.isNotBlank(startDate) && StringUtil.isNotBlank(endDate)) {
                    Date jdStarDate = DateUtil.parseDate(startDate, "yyyy-MM-dd HH:mm");
                    Date jdEndDate = DateUtil.parseDate(endDate, "yyyy-MM-dd HH:mm");
                    Date currdate = new Date();
                    if (currdate.before(jdStarDate)) {
                        status = "0";
                    } else if (currdate.after(jdEndDate)) {
                        status = "2";
                    } else {
                        status = "1";
                    }
                }
                if (StringUtil.isNotBlank(status)) {
                    if (!gsStatus.equals(status)) {
                        supplierProjectPubNotice.setGsStatus(status);
                        supplierProjectPubNoticeService.updateByPrimaryKey(supplierProjectPubNotice);
                    }

                }

            }
            System.out.println("JobDemo1：执行完毕=======================");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void lock(String key, String uuId) {
        for (; ; ) {

            System.out.println(redisService);
            boolean r = stringRedisTemplate.opsForValue().setIfAbsent(key, uuId);
            stringRedisTemplate.expire(key, 600, TimeUnit.SECONDS);

            if (r) {
                return;
            } else {
                throw new RuntimeException("已经存在的执行程序...");
            }
        }
    }

    public void unlock(String key, String uuId) {
        if (uuId.equals(stringRedisTemplate.opsForValue().get(key))) {
            stringRedisTemplate.delete(key);
        }
    }


}
